package com.zbkj.front.service.impl;

import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.diagnosis.DiagnosisUtils;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.google.common.collect.Lists;
import com.zbkj.common.enums.OrderStatusEnum;
import com.zbkj.common.enums.OrderTypeEnum;
import com.zbkj.common.exception.CommonException;
import com.zbkj.common.model.order.OrderDetail;
import com.zbkj.common.model.order.OrderInfo;
import com.zbkj.common.model.user.User;
import com.zbkj.common.request.order.ClientOrderSaveRequest;
import com.zbkj.common.response.order.OrderSucceResponse;
import com.zbkj.front.config.AliConfig;
import com.zbkj.front.service.OrderHandleService;
import com.zbkj.front.service.PaymentService;
import com.zbkj.service.service.order.OrderDetailService;
import com.zbkj.service.service.order.OrderInfoService;
import com.zbkj.service.service.user.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class AlipayPaymentService implements PaymentService {

    @Resource
    private AlipayClient alipayClient;
    @Resource
    private AliConfig alipayConfig;
    @Resource
    private OrderHandleService orderHandleService;
    @Resource
    private OrderInfoService orderInfoService;
    @Resource
    private UserService userService;
    @Resource
    private OrderDetailService orderDetailService;

    @Override
    public String pay(Map<String, Object> params) throws AlipayApiException {

        OrderSucceResponse succeResponse = orderHandleService.orderSave((ClientOrderSaveRequest) params.get("saveRequest"));
        OrderInfo orderInfo = orderInfoService.getOrderInfo(null, succeResponse.getOrderNo());
        // 构造请求参数以调用接口
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();

//        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //回调Url
        request.setNotifyUrl(alipayConfig.getNotifyUrl());
        request.setReturnUrl(alipayConfig.getReturnUrl()); // 同步跳转测试地址

//        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        // 设置商户订单号
        model.setOutTradeNo(succeResponse.getOrderNo());
        // 设置订单总金额
        model.setTotalAmount(orderInfo.getTotalAmount().toString());
        // 设置订单标题
        model.setSubject("BUY VIP");
        // 设置产品码
        model.setProductCode("FAST_INSTANT_TRADE_PAY");

        // 设置PC扫码支付的方式
        //model.setQrPayMode("1");

        // 设置商户自定义二维码宽度
        //model.setQrcodeWidth(100L);

        // 设置订单绝对超时时间
        String expireDate = LocalDateTime.now().plusMinutes(5).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        model.setTimeExpire(expireDate);

        request.setBizModel(model);

        AlipayTradePrecreateResponse response = alipayClient.execute(request);

        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);

        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            System.out.println(diagnosisUrl);
        }

        return pageRedirectionData;
    }

    @Override
    public OrderSucceResponse wxpay(Map<String, Object> params) throws AlipayApiException {
        return null;
    }

    @Override
    public String callback(HttpServletRequest request, HttpServletResponse response) {

        try {
            // 提取请求参数
            Map<String, String> params = new HashMap<String, String>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                params.put(name, valueStr);
            }

            log.info("------支付宝支付收到支付通知------，报文：【{}】", JSONUtil.toJsonStr(params));
            boolean valid = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipayPublicKey(), "utf-8", "RSA2");

            if (valid) {
                String outTradeNo = params.get("out_trade_no");
                //交易状态
                String tradeStatus = params.get("trade_status");
                log.info("签名验证成功，订单号：【{}】，状态为：【{}】", outTradeNo, tradeStatus);
                if (!"TRADE_SUCCESS".equals(tradeStatus)) {
                    return "success";
                }

                OrderInfo orderInfo = orderInfoService.getOrderInfoByOrderNo(outTradeNo);
                Integer status = orderInfo.getOrderType();
                if (!OrderStatusEnum.isOrderStatus1(orderInfo.getOrderStatus())) {
                    return "success";
                    //throw new CommonException("订单状态已变更");
                }
                User user = userService.getUserById(orderInfo.getUserId());
                userService.userValidCheck(user);
                List<OrderDetail> orderDetailList = orderDetailService.getListByOrderIds(Lists.newArrayList(orderInfo.getId()));
                if (OrderTypeEnum.isType1(orderInfo.getOrderType())) {
                    //申请报告订单开通处理
                    orderHandleService.orderStatusUpdate(orderInfo, status, Lists.newArrayList(OrderStatusEnum.ORDER_STATUS1.getStatus()), null);
                } else {
                    //年卡流量包订单开通处理
                    orderHandleService.orderApprovalOpen(user, orderInfo, orderDetailList);
                }
                return "success";
            }
        } catch (Exception e) {
            log.error("支付宝回调处理失败：【{}】", e.getMessage());
        }
        log.info("------支付宝支回调处理失败---------");
        return "fail";
    }

}
